<script setup>
import api from '../api/user_api.js'  // 注意修改API路径为User相关接口
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'
import attraction_api from "../api/attraction_api.js";
import favoritesApi from '../api/favorites_api.js'
import loginApi from '../api/login_api.js'
import { useRouter } from 'vue-router'
// ---------------------------
// 1. 数据定义区域
// ---------------------------

// 表格相关数据
const tableData = ref([]);  // 表格展示数据
const total = ref(0);      // 总记录数（用于分页）
const currentUserId = ref(null);
// 编辑对话框状态
const editWinVisible = ref(false);  // 对话框显示/隐藏
// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});

// 默认头像URL
const defaultAvatar = 'https://easy-travel.oss-cn-beijing.aliyuncs.com/36b1def4-e42e-4ec6-97c6-73e9b43cbf7d.png';

// 查询参数（分页+条件）
const searchObj = ref({
  current: 1,    // 当前页码
  limit: 10,     // 每页条数
  username: '',  // 按用户名查询
  email: ''      // 按邮箱查询
});

// 编辑/新增表单数据
const obj = ref({});

const reseve =ref({});
// 修改密码相关数据
const changePasswordVisible = ref(false);
const changePasswordMethod = ref('old'); // 'old' 表示通过旧密码修改，'email' 表示通过邮箱验证码修改
const router = useRouter(); // 添加路由实例用于页面跳转
const changePasswordForm = ref({
  oldPassword: '',
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
});
const changePasswordCodeText = ref('发送验证码');
const changePasswordIsCounting = ref(false);
let changePasswordTimer = null;

// ---------------------------
// 2. 生命周期钩子
// ---------------------------

// 页面加载时初始化数据
onMounted(async () => {
  await search();  // 调用查询方法
});

// ---------------------------
// 3. 核心业务逻辑
// ---------------------------

/**
 * 分页查询用户数据
 * 根据searchObj中的条件加载数据
 */
const search = async () => {
  const result = await api.page(searchObj.value);
  tableData.value = result.data;  // 赋值表格数据
  total.value = result.count;     // 赋值总记录数
}
/**
 * 取消编辑
 * 清空表单数据并关闭对话框
 */
const editCancel = () => {
  obj.value = {};  // 清空表单
  editWinVisible.value = false;  // 关闭对话框
}
/**
 * 提交表单（新增或编辑）
 * 根据是否有ID判断操作类型
 */
const editCommit = async () => {
  // 有ID则执行编辑，无ID则执行新增
  if (obj.value.id) {
    await api.edit(obj.value);  // 编辑接口
  } else {
    await api.add(obj.value);   // 新增接口
  }

  search();  // 刷新表格
  editWinVisible.value = false;  // 关闭对话框
}

// ---------------------------
// 4. 事件处理方法
// ---------------------------

/**
 * 搜索按钮点击事件
 * 重置页码为1后执行查询
 */
const handleSearch = () => {
  searchObj.value.current = 1;  // 重置页码
  search();
}
const handleUploadSuccess = (response,file) => {

  obj.value.photo=response.data;
};
/**
 * 分页大小改变事件
 * @param {Number} val - 新的每页条数
 */
const handleSizeChange = (val) => {
  searchObj.value.limit = val;  // 更新每页条数
  search();
}

/**
 * 页码改变事件
 * @param {Number} val - 新的页码
 */
const handleCurrentChange = (val) => {
  searchObj.value.current = val;  // 更新当前页码
  search();
}

/**
 * 新增用户
 * 初始化表单并打开对话框
 */
const handleAdd = () => {
  // 初始化新增表单默认值
  obj.value = {
    username: '',
    email: '',
    photo: '',
    password: ''
  };
  editWinVisible.value = true;  // 打开对话框
}

// /**
//  * 编辑用户
//  * @param {Number} index - 行索引
//  * @param {Object} row - 行数据
//  */
const handleEdit = (index, row) => {
  // 深拷贝避免直接修改表格数据
  obj.value = lodash.clone(row);
  editWinVisible.value = true;  // 打开对话框
  console.log(index, row);
}

// /**
//  * 删除用户
//  * @param {Number} index - 行索引
//  * @param {Object} row - 行数据
//  */
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该用户吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);  // 调用删除接口
        searchObj.value.current = 1;  // 重置页码
        search();  // 刷新数据
      })
      .catch(() => {
        // 取消删除时不做处理
      })
}
// 判断是否为管理员登录
const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}

// 修改密码相关方法
const showChangePasswordDialog = async () => {
  try {
    // 获取当前登录用户的信息
    const userInfo = await loginApi.userinfo();
    if (userInfo && userInfo.email) {
      changePasswordForm.value.email = userInfo.email;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }

  changePasswordVisible.value = true;
};

const sendChangePasswordCode = async () => {
  if (!changePasswordForm.value.email) {
    ElMessageBox.alert('请输入邮箱地址', '提示', { type: 'warning' });
    return;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(changePasswordForm.value.email)) {
    ElMessageBox.alert('请输入正确的邮箱格式', '提示', { type: 'warning' });
    return;
  }

  try {
    const res = await loginApi.sendUserEmailCode(changePasswordForm.value.email);
    if (res) {
      ElMessageBox.alert('验证码已发送，请查收邮箱', '提示', { type: 'success' });
      startChangePasswordCountdown();
    } else {
      ElMessageBox.alert('验证码发送失败', '提示', { type: 'error' });
    }
  } catch (error) {
    ElMessageBox.alert('验证码发送失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

const startChangePasswordCountdown = () => {
  changePasswordIsCounting.value = true;
  let count = 60;
  changePasswordCodeText.value = `${count}秒后重发`;

  changePasswordTimer = setInterval(() => {
    count--;
    if (count > 0) {
      changePasswordCodeText.value = `${count}秒后重发`;
    } else {
      changePasswordCodeText.value = '发送验证码';
      changePasswordIsCounting.value = false;
      clearInterval(changePasswordTimer);
    }
  }, 1000);
};

const changePassword = async () => {
  // 表单验证
  if (changePasswordMethod.value === 'old') {
    // 通过旧密码修改
    if (!changePasswordForm.value.oldPassword ||
        !changePasswordForm.value.newPassword ||
        !changePasswordForm.value.confirmPassword) {
      ElMessageBox.alert('请填写所有必填项', '提示', { type: 'warning' });
      return;
    }

    if (changePasswordForm.value.newPassword !== changePasswordForm.value.confirmPassword) {
      ElMessageBox.alert('两次输入的密码不一致', '提示', { type: 'warning' });
      return;
    }

    if (changePasswordForm.value.newPassword.length < 6) {
      ElMessageBox.alert('密码长度不能少于6位', '提示', { type: 'warning' });
      return;
    }

    try {
      const res = await api.updatePassword(
          changePasswordForm.value.oldPassword,
          changePasswordForm.value.newPassword
      );

      if (res !== undefined) {
        ElMessageBox.alert('密码更新成功,请重新登陆', '提示', { type: 'success' });
        changePasswordVisible.value = false;
        // 添加跳转到登录页面
        router.push('/login');
      } else {
        ElMessageBox.alert('密码更新失败', '提示', { type: 'error' });
      }
    } catch (error) {
      ElMessageBox.alert('密码更新失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
    }
  } else {
    // 通过邮箱验证码修改
    if (!changePasswordForm.value.email ||
        !changePasswordForm.value.code ||
        !changePasswordForm.value.newPassword ||
        !changePasswordForm.value.confirmPassword) {
      ElMessageBox.alert('请填写所有必填项', '提示', { type: 'warning' });
      return;
    }

    if (changePasswordForm.value.newPassword !== changePasswordForm.value.confirmPassword) {
      ElMessageBox.alert('两次输入的密码不一致', '提示', { type: 'warning' });
      return;
    }

    if (changePasswordForm.value.newPassword.length < 6) {
      ElMessageBox.alert('密码长度不能少于6位', '提示', { type: 'warning' });
      return;
    }

    try {
      const res = await api.resetPassword(
          changePasswordForm.value.email,
          changePasswordForm.value.code,
          changePasswordForm.value.newPassword
      );

      if (res) {
        ElMessageBox.alert('密码重置成功,请重新登陆', '提示', { type: 'success' });

        changePasswordVisible.value = false;
        router.push('/login');

        // 清除倒计时
        if (changePasswordTimer) {
          clearInterval(changePasswordTimer);
          changePasswordTimer = null;
        }
      } else {
        ElMessageBox.alert('密码重置失败', '提示', { type: 'error' });
      }
    } catch (error) {
      ElMessageBox.alert('密码重置失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
    }
  }
};

const cancelChangePassword = () => {
  changePasswordVisible.value = false;

  // 清除倒计时
  if (changePasswordTimer) {
    clearInterval(changePasswordTimer);
    changePasswordTimer = null;
  }

  changePasswordCodeText.value = '发送验证码';
  changePasswordIsCounting.value = false;

  // 重置表单
  changePasswordForm.value = {
    oldPassword: '',
    email: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  };
  changePasswordMethod.value = 'old';
};

// 处理头像加载错误
const handleAvatarError = (event) => {
  event.target.src = defaultAvatar;
};
</script>


<template>
  <div class="user-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="searchObj.email" placeholder="请输入邮箱" clearable style="width: 250px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item v-if="isAdminLogin()">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <!-- 添加修改密码按钮 -->
      <el-form-item  v-if="!isAdminLogin()">
        <el-button type="warning" @click="showChangePasswordDialog">修改密码</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
      <!--      <el-table-column label="ID" width="80" align="center">-->
      <!--        <template #default="scope">-->
      <!--          {{ scope.row.id }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="用户名" min-width="150">
        <template #default="scope">
          <div style="display: flex; align-items: center; padding-left: 10px;">
            {{ scope.row.username }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="200">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>邮箱: {{ scope.row.email }}</div>
              <div>ID: {{ scope.row.id }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.email }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="头像" min-width="200">
        <template #default="scope">
          <el-image
              :src="scope.row.photo ? scope.row.photo : defaultAvatar"
              class="img-avatar"
              :preview-src-list="[scope.row.photo ? scope.row.photo : defaultAvatar]"
              fit="cover"
              @error="handleAvatarError"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button
              v-if="isAdminLogin()"
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
          >
            删除
          </el-button>
          <!--          <el-button  v-if="!isAdminLogin()" size="small" @click="handleSelect(scope.$index, scope.row)">-->
          <!--            收藏-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />
    <!--    收藏弹窗 -->
    <el-dialog v-model="selectAttractionWinVisible" title="选择景点" width="500px" :close-on-click-modal="false">
      <el-form :model="reseve" label-width="100px">

        <el-form-item label="景点" label-width="100px">
          <el-select
              v-model="reseve.attraction_id"
              placeholder="请选择景点"
              style="width: 240px">
            <el-option
                v-for="item in attractions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelFavorite">取消</el-button>
          <el-button type="primary" @click="submitFavorite">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑用户" width="500px">
      <el-form :model="obj" label-width="100px">

        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" autocomplete="off" disabled />
          <div class="el-form-item__help">ID为系统自动生成，不可修改</div>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="obj.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="obj.email" autocomplete="off" />
        </el-form-item>
        <!--        <el-form-item label="密码">-->
        <!--          <el-input v-model="obj.password" type="password" autocomplete="off" />-->
        <!--        </el-form-item>-->
        <el-form-item label="头像":label-width="100">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleUploadSuccess"

          >
            <img :src="obj.photo ? obj.photo : defaultAvatar" @error="handleAvatarError" class="avatar-preview" />

          </el-upload>

        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordVisible" title="修改密码" width="500px" :close-on-click-modal="false">
      <el-form :model="changePasswordForm" label-width="100px">
        <!-- 修改方式选择 -->
        <el-form-item label="修改方式">
          <el-radio-group v-model="changePasswordMethod">
            <el-radio label="old">通过旧密码修改</el-radio>
            <el-radio label="email">通过邮箱验证码修改</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 通过旧密码修改 -->
        <template v-if="changePasswordMethod === 'old'">
          <el-form-item label="旧密码" required>
            <el-input v-model="changePasswordForm.oldPassword" type="password" placeholder="请输入旧密码" autocomplete="off" show-password />
          </el-form-item>
          <el-form-item label="新密码" required>
            <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="请输入新密码" autocomplete="off" show-password />
          </el-form-item>
          <el-form-item label="确认密码" required>
            <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" autocomplete="off" show-password />
          </el-form-item>
        </template>

        <!-- 通过邮箱验证码修改 -->
        <template v-else>
          <el-form-item label="邮箱" required>
            <el-input v-model="changePasswordForm.email" placeholder="请输入邮箱地址" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="验证码" required>
            <div style="display: flex; gap: 10px;">
              <el-input v-model="changePasswordForm.code" placeholder="请输入验证码" autocomplete="off" />
              <el-button
                  @click="sendChangePasswordCode"
                  :disabled="changePasswordIsCounting"
                  type="primary"
              >
                {{ changePasswordCodeText }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="新密码" required>
            <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="请输入新密码" autocomplete="off" show-password />
          </el-form-item>
          <el-form-item label="确认密码" required>
            <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" autocomplete="off" show-password />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChangePassword">取消</el-button>
          <el-button type="primary" @click="changePassword">
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.img-avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
}
</style>
